<?php

class AdminController extends Controller
{

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules()
	{
		return array(
			array('deny',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index', 'create', 'update', 'delete'),
				'users'=>array('?'),
			),
		);
	}

	public function actionCreate()
	{
        $model=new Admin(self::$CREATE);

        // ajax验证
        $this->performAjaxValidation($model);

		if(isset($_POST['Admin']))
		{
            $model->attributes = $_POST['Admin'];

			if($model->save())
				BlogTool::successRedirect('添加管理员成功!', 'admin/index');
		}
		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionUpdate($id)
	{
        $model = $this->loadModel($id, self::$UPDATE);
        $this->performAjaxValidation($model);

		if(isset($_POST['Admin']))
		{
			$model->attributes=$_POST['Admin'];
			if($model->save())
				BlogTool::successRedirect('修改管理员成功!', 'admin/index');
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionDelete($id)
	{
	    $this->loadModel($id, self::$DELETE)->delete();
        BlogTool::successRedirect('成功删除管理员', 'admin/index');
	}

	public function actionIndex()
	{
        $model = new Admin();

        // 筛选条件
        $criteria = new CDbCriteria();
        $criteria->select = 'id, admin_name, admin_last_ip, admin_last_time, admin_reg_time';
        $criteria->order = 'id asc';

        // 分页
        $pages = parent::showPager($model, $criteria);

        $data = $model->findAll($criteria);

        $this->render('index',array(
			'data'=>$data,
            'pager'=>$pages
		));
	}

	public function loadModel($id, $sec)
	{
		$admin = new Admin($sec);
        $model = $admin->findByPk((int)$id);

		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	protected function performAjaxValidation($model)
	{
        // ajax验证
        if(isset($_POST['ajax']) && $_POST['ajax']==='admin-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
	}
}
